﻿using Identity_MVC.ViewModels;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Identity_MVC.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace Identity_MVC.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }


        public IActionResult RedirectToLocal(string returnUrl)
        {
            //判断是否是本地url(本服务器的url地址)
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }

            return RedirectToAction(nameof(HomeController.Index), "Home");
        }

        public IActionResult Login(string returnUrl = "")
        {
            ViewData["ReturnUrl"] = returnUrl;

            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="LoginViewModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Login(LoginViewModel LoginViewModel, string returnUrl = "")
        {

            if (ModelState.IsValid)
            {
                ViewData["ReturnUrl"] = returnUrl;

                //Email作为用户名
                var user = await _userManager.FindByEmailAsync(LoginViewModel.Email);

                if (user == null)
                {
                    ModelState.AddModelError("Email", "邮箱不存在!");
                    return View();
                }

                //登录
                await _signInManager.SignInAsync(user, new AuthenticationProperties() { IsPersistent = true });

                return RedirectToLocal(returnUrl);
            }

            return View();
        }

        public IActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="registerViewModel"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> Register(RegisterViewModel registerViewModel, string returnUrl = "")
        {

            if (ModelState.IsValid)
            {
                ViewData["ReturnUrl"] = returnUrl;

                var identityUser = new ApplicationUser()
                {
                    UserName = registerViewModel.Email,
                    NormalizedUserName = registerViewModel.Email,
                    Email = registerViewModel.Email
                };

                //注册
                var identityResult = await _userManager.CreateAsync(identityUser, registerViewModel.Password);

                if (identityResult.Succeeded)
                {
                    //注册成功后直接登录
                    await _signInManager.SignInAsync(identityUser, new AuthenticationProperties()
                    {
                        IsPersistent = true
                    });

                    return RedirectToLocal(returnUrl);
                }
                else
                {
                    AddErrors(identityResult);
                }
            }

            return View();
        }


        private void AddErrors(IdentityResult identityResult)
        {
            foreach (var error in identityResult.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();

            return RedirectToAction("Index", "Home");
        }
    }
}
